//
//  QuestionViewController.m
//  zhijian
//
//  Created by lcb on 2019/1/18.
//  Copyright © 2019 lcb. All rights reserved.
//

#import "QuestionViewController.h"
#import "QuestionDetailViewController.h"
#import "QuestionPublicViewController.h"
#import "TabBarHeaderView.h"
#import "QuestionModel.h"
#import <PYSearch/PYSearch.h>
#import "QuestionCell_None.h"
@interface QuestionViewController ()<UITableViewDelegate,UITableViewDataSource,TabBarHeaderViewDelegate,PYSearchViewControllerDelegate,PYSearchViewControllerDataSource>
@property(nonatomic,strong) TabBarHeaderView * searchView;
@property(nonatomic,strong) UIView *nvisearchView ;
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic, strong) BaseRefresh *ymRefresh;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property(nonatomic,assign) NSInteger currentPage;
@property(nonatomic,strong) NSString *orderby;
@property (strong, nonatomic) UIButton *editImageView;
@property(nonatomic,strong)PYSearchViewController *searchViewController;
@property(nonatomic,strong)NSMutableArray *searchDataArray;
@end

@implementation QuestionViewController
@synthesize orderby=_orderby;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.titleView =self.searchView;
    //
    if (!_dataSource) {
        _dataSource =[NSMutableArray array];
    }
    self.currentPage =1;
    self.orderby = @"2";
    //eg:3
    _ymRefresh = [[BaseRefresh alloc] init];
    __weak __typeof(self)weakSelf = self;
    [_ymRefresh normalModelRefresh:self.tableView refreshType:RefreshTypeDouble firstRefresh:YES timeLabHidden:NO stateLabHidden:YES dropDownBlock:^{
        NSLog(@"下拉");
        if ([weakSelf.tableView.mj_footer isRefreshing]) {
            return;
        }
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    } upDropBlock:^{
        NSLog(@"上拉");
        if ([weakSelf.tableView.mj_header isRefreshing]) {
            return;
        }
        weakSelf.currentPage++;
        [weakSelf loadData];
    }];
}
-(TabBarHeaderView*)searchView
{
    if (!_searchView) {
        _searchView=[[TabBarHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44) item:@[@"热门咨询", @"最新咨询"]];
        _searchView.delegate = self;
    }
    return _searchView;
}
-(void)searchClickWithButton:(NSInteger)button
{
    switch (button) {
        case 0:
            {
                self.orderby = @"2";
                 [self.tableView.mj_header beginRefreshing];
            }
            break;
        case 1:
            {
                self.orderby = @"1";
                 [self.tableView.mj_header beginRefreshing];
            }
            break;
        default:
            break;
    }
}
-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        //
    
        _nvisearchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        _nvisearchView.backgroundColor=navColor;
        _nvisearchView.userInteractionEnabled=YES;
        UISearchBar*searchBar = [[UISearchBar alloc]init];
        searchBar.frame=CGRectMake(10,2,SCREEN_WIDTH-20,40);
        searchBar.layer.cornerRadius=18;
        searchBar.layer.masksToBounds=YES;
        //边框线粗细
        [searchBar.layer setBorderWidth:8];
        //设置边框为白色是为了盖住UISearchBar上的灰色
        [searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];
        searchBar.placeholder=@"请输入搜索的关键字";
        searchBar.userInteractionEnabled=YES;
        [_nvisearchView addSubview:searchBar];
        UIButton *tag =[UIButton buttonWithType:UIButtonTypeCustom];
        tag.frame=CGRectMake(0, 0, SCREEN_WIDTH, 40);
        [tag addTarget:self action:@selector(searchbar) forControlEvents:UIControlEventTouchUpInside];
        [_nvisearchView addSubview:tag];
        _tableView.tableHeaderView =_nvisearchView;
     
        if ([[BaseShare sharedBaseShare] getUser].userType==3) {
             self.editImageView.frame =CGRectMake(SCREEN_WIDTH-60, SCREEN_HEIGHT-LY_IPHONE_BOTTOM_HEIGHT-120, 60, 60);
        }
    }
    return _tableView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
//section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString * identifier =  @"QuestionCell_None";
    QuestionModel *qModel =[self.dataSource objectAtIndex:indexPath.section];
    if (qModel.questionPics.length>0) {
        identifier =  @"QuestionCell_Image";
    }
    Class mClass =  NSClassFromString(identifier);
    
    BaseViewCell * cell =  [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[mClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
  
    cell.baseModel = qModel;
    cell.indexPath =indexPath;
    ////// 此步设置用于实现cell的frame缓存，可以让tableview滑动更加流畅 //////
    
    cell.sd_tableView = tableView;
    cell.sd_indexPath = indexPath;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:self.tableView];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    QuestionModel *qModel =[self.dataSource objectAtIndex:indexPath.section];
    QuestionDetailViewController *list =[[QuestionDetailViewController alloc] init];
    list.questionModel = qModel;
    [self.navigationController pushViewController:list animated:YES];
}

-(void)loadData
{
    __weak __typeof(self)weakSelf = self;
    [[Api sharedApi] questionList:self.orderby content:@"" page:[NSString stringWithFormat:@"%ld",(long)self.currentPage] pageSize:@"20" callback:^(ApiResponse *response,NSString* errorMsg) {
        if (response!=nil && response.code==0 && response.data) {
            NSArray * listModel = [NSArray yy_modelArrayWithClass:[QuestionModel class] json:response.data];
           if (self.currentPage==1) {
                [self.dataSource removeAllObjects];
                self.dataSource = [NSMutableArray arrayWithArray:listModel];
            }else{
                [self.dataSource addObjectsFromArray:listModel];
            }
            if ([weakSelf.tableView.mj_header isRefreshing]) {
                [weakSelf.tableView.mj_header endRefreshing];
                if (listModel.count==0) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            if ([weakSelf.tableView.mj_footer isRefreshing]) {
                if (listModel.count==0) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
           
        }else{
            [BaseToast show:response.message];
        }
        
        [weakSelf.tableView reloadData];
    }];
}
-(UIButton*)editImageView
{
    if (!_editImageView) {
        _editImageView =[UIButton buttonWithType:UIButtonTypeCustom];
        _editImageView.frame =CGRectMake(0, 100, 60, 60);
        _editImageView.backgroundColor=navColor;
        _editImageView.layer.cornerRadius = 60/2;
        _editImageView.layer.masksToBounds=YES;
        [_editImageView setImage:[UIImage imageNamed:@"pen"] forState:UIControlStateNormal];
        _editImageView.imageView.contentMode=UIViewContentModeScaleAspectFit;
        [_editImageView addTarget:self action:@selector(publishQuestion) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_editImageView];
        [self.tableView bringSubviewToFront:_editImageView];
    }
    return _editImageView;
}
-(void)publishQuestion{
    QuestionPublicViewController *publish =[[QuestionPublicViewController alloc] init];
    publish.type =@"questions";
    [self.navigationController pushViewController:publish animated:YES];
}
//
-(void)searchbar
{
    _searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:@[] searchBarPlaceholder:@"关键字搜索"];
    _searchViewController.delegate = self;
    _searchViewController.dataSource=self;
    _searchViewController.showHotSearch = NO;
    UIImage *image = [UIImage imageNamed:@"back"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    _searchViewController.backBarButtonItem =barButton;
    _searchViewController.searchViewControllerShowMode = PYSearchResultShowModePush;
    [self.navigationController pushViewController:self.searchViewController animated:YES];
}
-(void)backAction{
    self.searchViewController.searchBar.delegate=nil;
    self.searchViewController.searchBar.text =@"";
    [self.searchViewController.navigationController popViewControllerAnimated:YES];
}
#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length) { // 与搜索条件再搜索
        [self search:searchText];
    }
}
- (UITableViewCell *)searchSuggestionView:(UITableView *)searchSuggestionView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseViewCell *  cell = [[QuestionCell_None alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"QuestionCell_None"];
    QuestionModel *qModel =[self.searchDataArray objectAtIndex:indexPath.row];
    cell.baseModel=qModel;
    return cell;
}
- (NSInteger)searchSuggestionView:(UITableView *)searchSuggestionView numberOfRowsInSection:(NSInteger)section
{
    return self.searchDataArray.count;
}

- (NSInteger)numberOfSectionsInSearchSuggestionView:(UITableView *)searchSuggestionView
{
    return 1;
}
- (CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (void)searchViewController:(PYSearchViewController *)searchViewController didSelectSearchSuggestionAtIndexPath:(NSIndexPath *)indexPath
                   searchBar:(UISearchBar *)searchBar
{
    QuestionModel *qModel =[self.searchDataArray objectAtIndex:indexPath.row];
    QuestionDetailViewController *question =[[QuestionDetailViewController alloc] init];
    question.questionModel = qModel;
    [self.navigationController pushViewController:question animated:YES];
}
-(void)didClickBack:(PYSearchViewController *)searchViewController
{
    self.searchViewController.searchBar.delegate=nil;
    self.searchViewController.searchBar.text =@"";
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)didClickCancel:(PYSearchViewController *)searchViewController
{
    self.searchViewController.searchBar.delegate=nil;
    self.searchViewController.searchBar.text =@"";
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)search:(NSString*)text
{
    __weak __typeof(self)weakSelf = self;
    [[Api sharedApi] questionList:self.orderby content:text page:@"1" pageSize:@"20" callback:^(ApiResponse *response,NSString* errorMsg) {
        if (response!=nil && response.code==0 && response.data) {
            NSArray * listModel = [NSArray yy_modelArrayWithClass:[QuestionModel class] json:response.data];
            [weakSelf.searchDataArray removeAllObjects];
            weakSelf.searchDataArray = [NSMutableArray arrayWithArray:listModel];
        }else{
            [BaseToast show:response.message];
        }
        [weakSelf.searchViewController.searchSuggestionView reloadData];
    }];
}
@end
